package com.activemq.schedule;

import cn.hutool.core.date.DateUtil;
import com.activemq.cluster.ClusterProd;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQMessageProducer;
import org.apache.activemq.AsyncCallback;
import org.apache.activemq.ScheduledMessage;

import javax.jms.*;
import java.util.UUID;

public class ScheduleProd {

    public static void main(String[] args) throws Exception {
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(ClusterProd.CLUSTER_URL);
        Connection connection = factory.createConnection();
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue(ClusterProd.QUEUE_NAME);
        ActiveMQMessageProducer producer = (ActiveMQMessageProducer) session.createProducer(queue);
        //延迟投递的时间
        long delay = 3000;
        //每4秒钟投递一次（时间间隔）
        long period = 4000;
        //repeat重复复次数
        int repeat = 5;
        for (int i = 0; i < 3; i++) {
            TextMessage textMessage = session.createTextMessage("delay 测试消息" + DateUtil.now() + "_" + UUID.randomUUID());
            textMessage.setJMSMessageID(textMessage.getText());
            textMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delay);
            textMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, period);
            textMessage.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, repeat);
            String msgId = textMessage.getJMSMessageID();
            producer.send(textMessage, new AsyncCallback() {
                @Override
                public void onException(JMSException e) {
                    System.out.println(msgId + "发送失败" + e.getMessage());
                }

                @Override
                public void onSuccess() {
                    System.out.println(msgId + "发送成功");
                }
            });
        }
        producer.close();
        session.close();
        connection.close();
    }
}

@Slf4j
class Rev {
    public static void main(String[] args) throws Exception {
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(ClusterProd.CLUSTER_URL);
        try (Connection connection = factory.createConnection()) {
            connection.start();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Queue queue = session.createQueue(ClusterProd.QUEUE_NAME);
            MessageConsumer consumer = session.createConsumer(queue);
            consumer.setMessageListener((msg) -> {
                try {
                    log.info("接收到消息" + ((TextMessage) msg).getText());
                } catch (JMSException e) {
                    log.error("出错", e);
                }
            });
            System.in.read();
            consumer.close();
            session.close();
        }
    }
}